﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using ChanTai.WebApi;

namespace ChanTaiApi
{
    partial class Service : ServiceBase
    {
        private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        internal static readonly string Name;
        static Service()
        {
            Name = System.Configuration.ConfigurationManager.AppSettings.Get("ServiceName");
            if (string.IsNullOrEmpty(Name)) Name = "ChenTaiApiService";
        }

        internal IDisposable Svhand { get; private set; }

        public Service()
        {
            InitializeComponent();
            ServiceName = Name;
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                Log.Info("启动服务");
                lock (this)
                {
                    if (Svhand == null)
                        Svhand = this.Start();
                }
                Log.Info("服务启动完成");
            }
            catch (Exception e)
            {
                Log.ErrorFormat("应用程序发生异常{0}", e);
                //throw;
            }
        }

        protected override void OnStop()
        {
            try
            {
                lock (this)
                {
                    if (Svhand == null) return;
                    Svhand.Dispose();
                    Log.Info("服务停止");
                }
            }
            catch (Exception e)
            {
                Log.ErrorFormat("应用程序发生异常{0}", e);
                throw;
            }
        }
    }
}
